<?php
namespace action;
use HomeArray\Home;
use HomeArray\HomeArray\HomeArray;


class Game{
  
    /**
     * 游戏规则获取
     * @return string[]
     */
    public function gameRule($connection){
        $data = array();
        $textModel = db("gametext");
        $text = $textModel->select();
        $text[0]['text'] =  strip_tags($text[0]['text']);
        $text[1]['text'] =  strip_tags($text[1]['text']);
        $db = db("users")->field("user_money,com_money")->where("id={$connection->uid}")->find();
        
//         $times =mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
//         $money = db("rebate")->where("user_id={$connection->uid} and add_time>{$times}")->sum("money");
//         $money = $money?$money:0;
        
//         $homeuserModel = db("home_user");
//         $list = $homeuserModel->where("user_id={$connection->uid} and home_id>1")->select();
        $list = array();
        $homeList = redisd() -> HgetAll("homeUser");
        if ($homeList){
            dump($homeList);
            foreach ($homeList as $k => $v){
                if (!empty($v) && $k != 1){
                    if (current($v) == $connection->uid){
                        $list[] = $k;
                    }
                }
            }
        }
        if($text){
            $data['ok'] = "1";
            $data['ws'] = 13;
            $data['ymoney'] = $db['com_money'];
            $data['list'] = $list;
            $data['user_money']=$db['user_money'];
            $data['rule'] = json_encode($text);
        }else{
            $data['ok'] = "2";
            $data['content'] = "无法获取规则";
        }
        return $data;
    }
    
    /**
     * 获取客服信息
     */
    public function kefu(){
        $data = array();
        $textModel = db("gametext");
        $text = $textModel->where("id=2")->find();
        if($text){
            $data['ok'] = "1";
            $data['rule'] = $text['text'];
        }else{
            $data['ok'] = "2";
            $data['content'] = "无法获取客服信息";
        }
        return $data;
    }
    
    /**
     * 提交充值
     * @param 充值金额数据 $json
     * @param 用户id $id
     */
    public function recharge($json,$id){
        $userModel = db("users");
        $rechargeModel = db("recharge");
        $a = $userModel->where("id={$id}")->count();
        $recharge = array();
        if($a>0){
            $recharge['user_id'] = $id;
            $recharge['money'] = $json['money'];
            $recharge['status'] = 0;
            $recharge['add_time'] = time();
            $id = $rechargeModel->insertGetId($recharge);
            if($id){
                $data['ok'] = "1";
               
            }else{
                $data['ok'] = "2";
                $data['content'] = "添加失败";
            }
        }else{
            $data['ok'] = "2";
            $data['content'] = "id错误获取失败";
        }
        $data['ws'] = "20";
        return $data;
    }
    
   /**
    * 提交提现
    * @param 金额 $json
    * @param 用户id $id
    */
    public function widthraswals($json,$id){
        $userModel = db("users");
        $rechargeModel = db("widthraswals");
        $a = $userModel->where("id={$id}")->count();
        $recharge = array();
        if($a>0){
            $recharge['user_id'] = $id;
            $recharge['money'] = $json['money'];
            $recharge['status'] = 0;
            $recharge['add_time'] = time();
            $recharge['tx_type'] = 1;
            $id = $rechargeModel->insertGetId($recharge);
            if($id){
                $data['ok'] = "1";
            }else{
                $data['ok'] = "2";
                $data['content'] = "添加失败";
            }
        }else{
            $data['ok'] = "2";
            $data['content'] = "id错误获取失败";
        }
        $data['ws'] = "21";
        return $data;
    }
    
    /**
     * 加入房间
     * @param unknown $homeId
     * 
     * 
     * 1、当时下单记录，当时庄家，当时的大小下注，当时的订单人数,
     * 
     */
    public function inHome($homeId,$connectionuid){
        $config = db("config")->where("id=2")->find();
        $ordernum = $config['values'];
        $home = redisd() -> HGet("homes",$homeId);
        if(!$home){
            return array("ok"=>2,"content"=>"无次房间或房间已解散");
        }
        //查询订单记录
        $dxlists['8'] = redisd() -> HVals("order{$homeId}8");
        $dxlists['7'] = redisd() -> HVals("order{$homeId}7");
        $countDa = $dxlists['8']?array_sum($dxlists['8']):0;
        $countXiao = $dxlists['7']?array_sum($dxlists['7']):0;
        foreach ($dxlists as $k => $v){
            foreach ($v as $row){
                foreach ($row as $res){                    
                    $lists[$k][] = $res;
                }
            }
        }
        $list = empty($lists)?0:$lists;
        $data = array(
            "ws"=>23,
            "ok"=>1,
            "da"=>$countDa,
            "xiao"=>$countXiao,
            "list"=>$list
        );
        $homeUsers = redisd() -> HGet("homeUser", $homeId);
        if ($homeUsers){
            if (!in_array($connectionuid, $homeUsers)){
                array_push($homeUsers, $connectionuid);
            }
        }else{
            $homeUsers = array($connectionuid);
        }
        redisd() -> HSet("homeUser", $homeId, $homeUsers);
        return $data; 
    }
    
    
    public function createHomeHeader($connection,$homeid){
        
        $config = db("config")->where("id=2")->find();
        $ordernum = $config['values'];
        $home = redisd() -> HGet("homes", $homeid);
        if(!$home){
            return array("ok"=>2,"content"=>"房间号错误");
        }
        $array = $this->getXian($homeid);
        $connection->homeid = $homeid;
        $homeUsers = redisd() -> HGet("homeUser", $homeid);
        if (!in_array($connection->uid, $homeUsers)){
            array_push($homeUsers, $connection -> uid);
            redisd() -> HSet("homeUser", $homeid, $homeUsers);   
        }  
        if($home['role_user_id']){
            $user = redisd() -> HGet("user", $home['role_user_id']);
            if (!$user){                
                $user = db("users") -> find($home['role_user_id']);
            }
            $name = $user['nickname'];
        }else{
            $name = 0;
        }
        //庄家
        if($home['role_user_id'] == $connection->uid){
            $z = 1;
        }else{
            $z = 0;
        }
        
        //订单人数
//         $num = $orderModel->where("home_id={$homeid} and num={$ordernum}")->count();
        $ordersnum[] = redisd() -> HVals("order{$homeid}8");
        $ordersnum[] = redisd() -> HVals("order{$homeid}7");
        $num = 0;
        foreach ($ordersnum as $v){
            foreach ($v as $row){                
                $num += count($row);
            }
        }
        $re = 0;
        if($homeid==1){
            $re = rand(70,99);
        }else{
            $re = count(redisd() -> HGet("homeUser", $homeid));
        }
        $money = getmoney($connection->uid);
        $josn = array(
            "ws"=>84,
            "ren"=>$re
        );
        getHomeConnections($connection,$josn);
        return array(
            "ok"=>1,
            "ws"=>24,
            "user_money"=>$money,
            "ren"=>$re,//人数
            "num"=>$num,//订单数
            "miao"=>date("s"),
            "da"=>$array['da'],
            "xiao"=>$array['xiao'],
            "money"=>$home['rolemoney'],
            "name"=>$name,
            "is_zhuang"=>$z
        );  
    }
    
    
    /**
     * 抢庄
     * @param 当前链接 $connection
     */
    public function robZhuang($connection,$message){
        $mymoney = getmoney($connection->uid);
        $money = $message['money'];
        $home = redisd() -> HGet("homes", $connection->homeid);
        $role_id = $home['role_user_id'];
        $roleMoney = $home['rolemoney'];
        $user = redisd() -> HGet("user", $connection->uid);
        if($role_id==$user['id']){
            return array("ok"=>2,"content"=>"已是庄家");
        }
        $homeAll = redisd() -> HVals("homes");
        foreach ($homeAll as $v){
            if ($connection->uid == $v['role_user_id']) {
                return array("ok"=>2,"content"=>"不能2个房间坐庄");
            }
        }
        if($money<1000){
            return array("ok"=>2,"content"=>"坐庄最低1000分");
        }  
        if($mymoney<$money){
            return array("ok"=>2,"content"=>"金额不足");
        }
        if($roleMoney>=$money){
            return array("ok"=>2,"content"=>"抢庄失败");
        }else{
            $home['role_user_id'] =$connection->uid;
            $home['rolemoney'] = $money;
            redisd() -> HSet("homes", $connection->homeid, $home);
            $arr = array("ws"=>80,"name"=>$user['nickname'],"money"=>$money);
            $connections =  getHomeConnections($connection,$arr,2);    
            return array("ok"=>1,"ws"=>"30","content"=>"抢庄成功");
         }
    }
    
    
    
    public function jiqirob($worker,$user){
        $money = $user['user_money'];
        $home = redisd() -> HGet("homes","1");
        $home['role_user_id'] = $user['id'];
        $home['rolemoney'] = $user['user_money'];
        redisd() -> HSet("homes", "1", $home);
        $arr = array("ws"=>80,"name"=>$user['nickname'],"money"=>$money);
        $json = json_encode($arr);
        foreach ($worker->connections as $connection){
            if(isset($connection->uid)&&isset($connection->homeid)&&$connection->homeid==1){
                $connection->send($json);
            }
        }
    } 
    
    
    /**
     * 获取一个房间的上下限制
     * @param unknown $homeid
     */
    public function getXian($homeid){
       $data = getOrderDaXiao($homeid);
       $home = redisd() -> HGet("homes", $homeid);
       $array['da'] = ($home['rolemoney']+$data['xiao'])-$data['da'];
       $array['xiao'] = ($home['rolemoney']+$data['da'])-$data['xiao'];
       return $array;
    }
    
    
    /**
     * 获得订单的大小上限，大小主
     * @param unknown $homeid
     */
    public function getorder($homeid){
        $data = getOrder($homeid);
        $home = redisd() -> HGet("homes", $homeid);  
        $array['da'] = ($home['rolemoney']+$data['xiao'])-$data['da'];
        $array['xiao'] = ($home['rolemoney']+$data['da'])-$data['xiao'];
        $array['yada'] = $data['da'];
        $array['yaxiao'] = $data['xiao'];
        $array['num'] = $data['num'];
        return $array;
    }
    
    /**
     * 下注
     * @param 发送的数据 $json
     * @param 当前链接 $connection
     */
    public function bet($json,$connection){
        $conModel = db("config");
        $money = getmoney($connection->uid);
        if($json['money']>$money&&$json['money']>0){
            return array("ok"=>2,"content"=>"余额 不足");
        }
        if($json['dian']!=7&&$json['dian']!=8){
            return array("ok"=>2,"content"=>"没有点");
        }
        if($json['money']<10){
            return array("ok"=>2,"content"=>"金额不对");
        }
        $homeAll = redisd() -> HVals("homes");
        foreach ($homeAll as $v){
            if ($connection->uid == $v['role_user_id']) {
                return array("ok"=>2,"content"=>"你已经是一个房间的房主，不能下注");
            }
        }
        $asd = $this->getorder($connection->homeid);
        $nums = $conModel->where("id=2")->find();
        $num = $nums['values'];
        $d = 0;
        if($json['dian']==7){
            $d=8;
            if(($asd['xiao']-$json['money'])<0){
                return array("ok"=>2,"content"=>"超过上限");
            }
        }elseif($json['dian']==8){
            $d=7;
            if(($asd['da']-$json['money'])<0){
                return array("ok"=>2,"content"=>"超过上限");
            }
        }
       /*  $cc = redisd() -> HGet("order".$connection->homeid.$d,$connection->uid);
        if($cc>0){
            return array("ok"=>2,"content"=>"不能对压");
        } */
        $yueMoney = $money-$json['money'];
        //添加订单
        $rInfo = redisd() -> HGet("order".$connection->homeid.$json['dian'], $connection -> uid);
        if ($rInfo){
            array_push($rInfo, $json['money']);
            $rUmoney = $rInfo;
        }else{
            $rUmoney = array($json['money']);
        }
        redisd() -> HSet("order".$connection->homeid.$json['dian'], $connection -> uid, $rUmoney);
        //$this->setRebate($connection->uid,$json['money']);//分销
        //分发订单
        $data = $this->getorder($connection->homeid);
        $data['ws'] = 81;
        $data['money'] = $json['money'];
        $data['dian'] = $json['dian'];
        $connections =  getHomeConnections($connection,$data);//分发
        //回复自己
        $user = redisd() -> HGet("user", $connection->uid);
        $user['user_money'] = $user['user_money'] - $json['money'];
        redisd() -> HSet("user", $connection->uid, $user);
        $daxiaomoney[] = redisd() -> HGet("order".$connection->homeid."8",$connection->uid);
        $daxiaomoney[] = redisd() -> HGet("order".$connection->homeid."7",$connection->uid);
        $summoney = 0;
        foreach ($daxiaomoney as $v){
            if (!empty($v)){
                $summoney += array_sum($v);
            }
        }
        return array("ws"=>31,"ok"=>1,"money"=>$yueMoney,"sum"=>$summoney);
    }
    
    
    /**
     * 机器人下注
     */
    public function aibet($worker,$user){
        $dian = rand(7,8);
        $array = array(100,500); 
        $num = getNum();
        $asd = $this->getorder(1);
        if($user['user_type']==1){//$user庄家id
            $xmoney = $array[rand(0,1)];//下注金额
            $money = $user['user_money'];
            if($dian==7){
                if(($asd['xiao']-$money)<0){
                    $dian = 8;
                }
            }elseif($dian==8){
                if(($asd['da']-$money)<0){
                    $dian = 7;
                }
            }
        }else{
            $model= db("ai");
            $js = $model->where("id=1")->find();
            $ai = $js;
            if($ai['num']==0){//本次第一次下注
                 $dian = 8;
                 $nus = 7;
                 $xmoney = $array[rand(0,1)];//下注金额
                 $model->where("id=1")->update(array("money"=>$xmoney,"num"=>$nus));  
            }else if($ai['num']==7){
                $dian = 7;
                $nus = 8;
                $xmoney = $ai['money'];
                $model->where("id=1")->update(array("money"=>$xmoney,"num"=>$nus));
            }else if($ai['num']==8){
                $dian = 8;
                $nus = 7;
                $xmoney =  $array[rand(0,1)];//下注金额
                $model->where("id=1")->update(array("money"=>$xmoney,"num"=>$nus));
            }
            
        }
        if($dian==7){
                if(($asd['xiao']-$xmoney)<0){
                    $dian = 10;
                }
        }elseif($dian==8){
                if(($asd['da']-$xmoney)<0){
                    $dian = 10;
                }
       }
        //添加订单
        $rInfo = redisd() -> HGet("order1".$dian, "jq_{$user['id']}");
        if ($rInfo){
            array_push($rInfo, $xmoney);
            $rUmoney = $rInfo;
        }else{
            $rUmoney = array($xmoney);
        }
        redisd() -> HSet("order1".$dian,"jq_{$user['id']}", $rUmoney);
        
        if($dian!=10){
            //分发订单
            $data = $this->getorder(1);
            $data['ws'] = 81;
            $data['money'] = $xmoney;
            $data['dian'] = $dian;
            $connections =  AiSendOrder($worker,$data);//分发
        }
        
   }
    
   
   /**
    * 发喇叭
    * @param unknown $json
    * @param unknown $connection
    */
   public function notice($json,$connection){
       $la = redisd() -> HGet("user", $connection -> uid);
       if($la['is_laba']!=1){
           return array("ok"=>2,"content"=>"无权");
       }
       $arr = array(
           "ws"=>83,
           "text"=>$la['nickname'].":".$json['text']
       );
       //发送给全体
       getHomeConnections($connection,$arr);
       return array("ws"=>34);
   }
   
   /**
    * 发congzi
    * @param unknown $json
    * @param unknown $connection
    */
   /* public function congzi($json,$connection){
      $db=db('kefu')->where('id=1')->find();
       $arr = array(
           'ok' =>1,
           "ws"=>111,
           "url"=>$db['url'],
           'name'=>$db['name'],
       );
       return $arr;
   } */
   
   /**
    * 下单后分佣金
    */
   public function setRebate($id,$money){
       $userModel = db("users");
       $rebateModel = db("rebate");
       $user = $userModel->where("id={$id}")->find();
       $configModel = db("config");
       $con = $configModel->where("con_type='rebate'")->select();
       $first = $con[0]['values'];
       $second = $con[1]['values'];
       $three = $con[2]['values'];
       $data = array(
           "buy_id"=>$id,
           "add_time"=>time(),
        /*    "tx_type"=>1 */
       );
       if($user['first_parent']){
           $firstmoney = $first*$money;
           $userModel->where("id={$user['first_parent']}")->setInc("user_money",$firstmoney);
           $data['user_id'] = $user['first_parent'];
           $data['money'] = $firstmoney;
           $rebateModel->insert($data);
           if($user['second_parent']){
               $secondmoney = $second*$money;
               $userModel->where("id={$user['second_parent']}")->setInc("user_money",$secondmoney);
               $data['user_id'] = $user['second_parent'];
               $data['money'] = $secondmoney;
               $rebateModel->insert($data);
               if($user['three_parent']){
                   $threemoney = $three*$money;
                   $userModel->where("id={$user['three_parent']}")->setInc("user_money",$threemoney);
                   $data['user_id'] = $user['three_parent'];
                   $data['money'] = $threemoney;
                   $rebateModel->insert($data);    
               }    
           }   
       }
   }
}